const ctx = wx.createCanvasContext('cover-preview');
var start_position = {}; //移动图片时手指起始坐标
var tempFilePath; //图片路径
var tempWidth; //图片初始宽度
var tempHeight; //图片初始高度
var old_x = 0; //图片初始x坐标
var old_y = 0; //图片初始y坐标
var _touches = 1; //触屏的手指数
var old_scale = 1; //原始放大倍数
var new_scale = 1; //新的放大倍数
var is_move = false; //是否移动
var bg_url;
var app = getApp();
var is_pay = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPoster : true,
    editState: false,
    defaultTxt: "祝你一帆风顺，二龙腾飞，三羊开泰， 四季平安，五福临门，六六大顺， 七星高照，八方来财，九九同心，十全十美。",
    inputValue: '祝你一帆风顺，二龙腾飞，三羊开泰， 四季平安，五福临门，六六大顺， 七星高照，八方来财，九九同心，十全十美。',
    perImgUrl: '',
    mainImg: './g-mainImg.png',
    mainImgWidth: 0,
    mainImgHeight: 0,
    p_width: '', // 页面宽度
    p_height: '', // 页面高度
    filePath: '',
    isGetImage: false,
    hide_canvas: true, //绘图层显示控制变量
    cardId: '',
    noQrCode : false,
    downLoadStatus : false

  },

  // 启动编辑文字
  editText() {
    this.setData({
      editState: true
    })
  },
  //去掉二维码
  editCode(e) {
    console.log(e.currentTarget.dataset)
    wx.navigateTo({
      url: '/pages/index/pay?cardId=' + e.currentTarget.dataset.cardId
    });
  },
  // input事件
  bindTextInput(event) {
    this.setData({
      inputValue: event.detail.value
    });
    console.log(this.data.inputValue);
  },
  editSubmit() {
    var _self = this;
    _self.setData({
      defaultTxt: _self.data.inputValue,
      editState: false
    })
  },
  // 取消编辑
  cancelEdit() {
    var _self = this;
    _self.setData({
      defaultTxt: _self.data.defaultTxt,
      inputValue: _self.data.inputValue,
      editState: false
    })
  },

  changeImg() {
    var _self = this;
    var m_width = _self.data.mainImgWidth;
    var m_height = _self.data.mainImgHeight;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        console.log(res);
        if (res.tempFilePaths.length > 0) {
          tempFilePath = res.tempFilePaths[0];
          wx.getImageInfo({
            src: tempFilePath,
            success: function (res) {
              // console.log(res.width)
              // console.log(res.height)
              tempWidth = res.width;
              tempHeight = res.height;
              console.log(tempWidth, tempHeight);
              console.log(m_width, m_height);
              if (m_width < tempWidth && m_height < tempHeight) {
                _self.setData({
                  isGetImage: true,
                  hide_canvas: false,
                })
                ctx.drawImage(tempFilePath, 0, 0, 375, res.height / res.width * 375);
                ctx.draw();
              } else {
                _self.setData({
                  mainImg: tempFilePath
                })
              }
            }
          })
        }
        // _self.setData({
        //   mainImg: tempFilePaths
        // });
      }
    })
  },
  //监听手指触摸事件，并判断是移动还是缩放，并记录初始状态
  canvas_start: function (e) {
    // console.log(e);
    var touches = e.touches.length;
    if (touches == 1) {
      _touches = 1;
      start_position = {
        x: e.touches[0].x,
        y: e.touches[0].y,
        timeStamp: e.timeStamp
      }
    } else if (touches == 2) {
      _touches = 2;
      start_position = {
        x: e.touches[0].x,
        y: e.touches[0].y,
        x1: e.touches[1].x,
        y1: e.touches[1].y,
        timeStamp: e.timeStamp
      }
    } else {
      _touches = 1;
    }
  },
  //监听手指移动事件，并做出相应调整
  canvas_move: function (e) {
    // console.log(e);
    var touches = e.touches.length;
    if (_touches == 1 && e.timeStamp - start_position.timeStamp > 150) {
      ctx.drawImage(tempFilePath, old_x + e.touches[0].x - start_position.x, old_y + e.touches[0].y - start_position.y, 375 * new_scale, tempHeight / tempWidth * 375 * new_scale);
      ctx.draw();
      is_move = true;
    } else if (_touches == 2 && e.timeStamp - start_position.timeStamp > 150) {
      var change_x = Math.abs(Math.abs(e.touches[0].x - e.touches[1].x) - Math.abs(start_position.x - start_position.x1));
      var change_y = Math.abs(Math.abs(e.touches[0].y - e.touches[1].y) - Math.abs(start_position.y - start_position.y1));
      if (change_x - change_y > 10) {
        old_scale = Math.abs(e.touches[0].x - e.touches[1].x) / Math.abs(start_position.x - start_position.x1);
      } else {
        old_scale = Math.abs(e.touches[0].y - e.touches[1].y) / Math.abs(start_position.y - start_position.y1);
      }
      ctx.drawImage(tempFilePath, old_x, old_y, 375 * old_scale * new_scale, tempHeight / tempWidth * 375 * old_scale * new_scale);
      ctx.draw();
      is_move = true;
    } else {
      is_move = false;
    }
  },
  //监听手指离开动作，并保存当前状态数据
  canvas_end: function (e) {
    // console.log(e);
    if (_touches == 1 && is_move) {
      old_x = old_x + e.changedTouches[0].x - start_position.x;
      old_y = old_y + e.changedTouches[0].y - start_position.y;
    } else if (_touches == 2 && is_move) {
      new_scale = old_scale * new_scale;
    }
  },
  //确定并上传背景图
  upload_bg: function () {
    var that = this;
    var screenWidth = wx.getSystemInfoSync().screenWidth;
    // console.log(screenWidth);
    wx.canvasToTempFilePath({
      x: 0,
      y: screenWidth / 750 * 400,
      width: screenWidth,
      height: screenWidth / 750 * 526,
      destWidth: screenWidth,
      screenHeight: screenWidth / 750 * 526,
      quality: 1,
      canvasId: 'cover-preview',
      success: function (res) {
        that.setData({
          hide_canvas: true,
          isGetImage: false,
          mainImg: res.tempFilePath
        })
        //res.tempFilePath即为生成的图片路径
        console.log(res.tempFilePath)
      }
    })
  },
  //取消图片预览编辑
  cancel_croper: function () {
    ctx.clearActions(); console.log(tempFilePath);
    this.setData({
      hide_canvas: true,
      isGetImage: false,
      mainImg: tempFilePath
      // edit_url: tempFilePath
    })
  },
  makePost() {
    wx.showLoading({
      title: '请稍候...',
    })
    var _self = this;
    var timer = null;
    timer = setInterval(function () {
      if (_self.data.downLoadStatus) {
        wx.hideLoading();
        _self.makePostDo();
        clearInterval(timer);
      } else {
      }
    }, 500);
  },
  makePostDo() {
    this.setData({
      getPoster: false,
    });
    var self = this;
    var p_width = self.data.p_width;
    var p_height = self.data.p_height;
    const ctx = wx.createCanvasContext('textCav');
    ctx.clearRect(0, 0, p_width, p_height);
    // ctx.drawImage('./g-bg.png', 0, 0, p_width, p_height);
    ctx.drawImage(self.data.picurl, 0, 0, p_width, p_height);
    
    // ctx.arc(p_width / 2 - 4, p_height * 100 / 1443, p_width * 60 / 750 , 0, 2 * Math.PI)
    // ctx.setLineWidth(5);
    // ctx.setStrokeStyle('red')
    // ctx.stroke()
    // ctx.clip()
    // ctx.drawImage(self.data.perImgUrl, p_width * 300 / 750, p_height * 20 / 1443, p_width * 132 / 750, p_width * 132 / 750);
    // ctx.restore()
    ctx.save()
    ctx.beginPath()
    ctx.moveTo(p_width * 70 / 750 + 10, p_height * 390 / 1443)
    ctx.lineTo(p_width * 680 / 750 - 10, p_height * 390 / 1443)
    ctx.arc(p_width * 680 / 750 - 10, p_height * 390 / 1443 + 10, 10, 1.5 * Math.PI, 2 * Math.PI)
    ctx.lineTo(p_width * 680 / 750, p_height * 390 / 1443 + p_height * 430 / 1334 - 10)
    ctx.arc(p_width * 680 / 750 - 10, p_height * 390 / 1443 + p_height * 430 / 1334 - 10, 10, 0, 0.5 * Math.PI)
    ctx.lineTo(p_width * 70 / 750 + 10, p_height * 390 / 1443 + p_height * 430 / 1334)
    ctx.arc(p_width * 70 / 750 + 10, p_height * 390 / 1443 + p_height * 430 / 1334 - 10, 10, 0.5 * Math.PI, 1 * Math.PI)
    ctx.lineTo(p_width * 70 / 750, p_height * 390 / 1443 + 10)
    ctx.arc(p_width * 70 / 750 + 10, p_height * 390 / 1443 + 10, 10, 1 * Math.PI, 1.5 * Math.PI)
    ctx.closePath()
    console.log(ctx);
    // ctx.setFillStyle('yellow')
    // ctx.fill()
    // ctx.clip()
    ctx.drawImage(self.data.mainImg, p_width * 90 / 750, p_height * 438 / 1443, p_width * 571 / 750, p_height * 392 / 1334)
    ctx.beginPath();
    ctx.setStrokeStyle('#a77b07')
    ctx.setLineWidth(2)
    ctx.strokeRect(p_width * 88 / 750, p_height * 436 / 1443, p_width * 571 / 750, p_height * 392 / 1334)
    // ctx.restore()
    ctx.setFontSize(14)
    ctx.setTextAlign('center')
    ctx.setFillStyle('#f01a1a')
    if (Math.floor(self.data.inputValue.length / 20) === 1) {
      ctx.fillText(self.data.inputValue.substring(0, 20), p_width * 375 / 750, p_height * 930 / 1443, p_width * 610 / 750)
      ctx.fillText(self.data.inputValue.substring(20), p_width * 375 / 750, p_height * 980 / 1443, p_width * 610 / 750)
    } else if (Math.floor(self.data.inputValue.length / 20) == 2) {
      ctx.fillText(self.data.inputValue.substring(0, 20), p_width * 375 / 750, p_height * 930 / 1443, p_width * 610 / 750)
      ctx.fillText(self.data.inputValue.substring(20, 40), p_width * 375 / 750, p_height * 980 / 1443, p_width * 610 / 750)
      ctx.fillText(self.data.inputValue.substring(40), p_width * 375 / 750, p_height * 1030 / 1443, p_width * 610 / 750)
    } else {
      ctx.fillText(self.data.inputValue, p_width * 375 / 750, p_height * 930 / 1443, p_width * 610 / 750)
    }
    if(!self.data.noQrCode){
      ctx.drawImage('../fgrh/f-qrCode.png', p_width * 283 / 750, p_height * 1050 / 1443, p_width * 184 / 750, p_height * 214 / 1334);
    }
    ctx.beginPath()
    ctx.arc(p_width / 2, p_height * 343 / 1443, p_width * 60 / 750, 0, 2 * Math.PI)
    ctx.closePath()
    ctx.setLineWidth(4);
    ctx.setStrokeStyle('red')
    ctx.stroke()
    ctx.clip()
    ctx.drawImage(self.data.perImgUrl, p_width * 309 / 750, p_height * 272 / 1443, p_width * 132 / 750, p_height * 132 / 1334);
    ctx.restore()
    ctx.draw();
  },
  saveImg() {
    var self = this;
    // 生成图片
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: self.data.p_width,
      height: self.data.p_height,
      destWidth: self.data.p_width * 2,
      destHeight: self.data.p_height * 2,
      canvasId: 'textCav',
      success(res) {
        console.log(res.tempFilePath);
        self.setData({
          filePath: res.tempFilePath
        })
      }
    });
    // 保存到相册
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              wx.saveImageToPhotosAlbum({
                filePath: self.data.filePath,
                success(res) {
                  console.log(res)
                  wx.showModal({
                    title: '保存图片成功',
                    content: '拜年卡已保存到您的手机相册，您可以在相册查看！',
                    showCancel: false
                  });
                }
              })
            }
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: self.data.filePath,
            success(res) {
              console.log(res)
              wx.showModal({
                title: '保存图片成功',
                content: '拜年卡已经保存到您的手机相册，您可以在相册查看！',
                showCancel: false
              });
            }
          })
        }
      }
    })
  },
  cancelBack() {
    this.setData({
      getPoster: true,
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var imgUrl = wx.getStorageSync("userInfo").avatarUrl;
    var  self = this;
    self.setData({
      perImgUrl: imgUrl,
      cardId: decodeURIComponent(options.cardId),
      is_pay: app.globalData.is_pay
    });

    perImgUrl: imgUrl
    console.log(self.data.perImgUrl);
    console.log(self.data.is_pay);

    var openId = wx.getStorageSync('openId');
    wx.request({
      url: 'https://bnk.xiutub.com/home/api/payinfo?openId=' + openId + '&tmpId=' + self.data.cardId,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res)
        console.log(res.data.res)
        if (res.data.res) { // 去掉二维码
          self.setData({
            noQrCode: true
          })
        }
      }
    })


    wx.downloadFile({
      url: 'https://bnk.xiutub.com/Uploads/temp/g-bg.png',
      success: function (res) {
        self.setData({
          'picurl': res.tempFilePath,
          'downLoadStatus' : true
        });
        console.log(res);
      }
    })

    wx.downloadFile({
      url: imgUrl, // 仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          console.log(res);
          self.setData({
            perImgUrl: res.tempFilePath
          });
        }
      }
    });
    try {
      const res = wx.getSystemInfoSync()
      console.log(res.model)
      console.log(res.pixelRatio)
      console.log(res.windowWidth)
      console.log(res.windowHeight)
      console.log(res.language)
      console.log(res.version)
      console.log(res.platform)
      this.setData({
        p_width: res.windowWidth,
        p_height: res.windowHeight
      })
    } catch (e) {
      // Do something when catch error
    }
    console.log(options);
    wx.createSelectorQuery().select('#mainImg').boundingClientRect(function (rect) {
      self.setData({
        mainImgWidth: rect.width, // 节点的宽度
        mainImgHeight: rect.height, // 节点的高度
      })
    }).exec()
  },
  

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
        title: '新年快乐，万事如意！和我一起来制作自己的拜年卡吧！',
      path: '/pages/index/index'
    }
  }
})